from loguru import logger
import pika
import os
from dotenv import load_dotenv

# 默认会加载项目根目录下的 .env 文件
load_dotenv()

# RabbitMQ 配置
RABBITMQ_HOST = os.getenv('RABBITMQ_HOST')
RABBITMQ_PORT = os.getenv('RABBITMQ_PORT')
RABBITMQ_USER = os.getenv('RABBITMQ_USER')
RABBITMQ_PASSWORD = os.getenv('RABBITMQ_PASSWORD')

# 创建消费者
def create_consumer(exchange, queue_name, routing_key, callback):
    # 创建连接
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(
            host=RABBITMQ_HOST,
            port=int(RABBITMQ_PORT),
            credentials=pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASSWORD)
        )
    )

    # 创建通道
    channel = connection.channel()

    # 创建交换机
    channel.exchange_declare(exchange=exchange, exchange_type='direct', durable=True)

    # 创建队列
    queue_obj = channel.queue_declare(queue=queue_name, durable=True)

    # 队列绑定
    channel.queue_bind(exchange=exchange, queue=queue_obj.method.queue, routing_key=routing_key)

    # 消费消息
    channel.basic_consume(queue=queue_obj.method.queue, on_message_callback=callback, auto_ack=True)

    logger.info("[*] 等待执行微博自动化任务... 按ctrl+c 退出")
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        logger.warning("[×] 微博自动化任务已退出")
    finally:
        channel.close()
        connection.close()


